<template>
  <div class="edit-page-wrap">
    <Head title="充电卡信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="edit-form-wrap"
        >
          <el-form-item label="卡面卡号" prop="cardNum">
            <el-input
              v-model.trim="ruleForm.cardNum"
              placeholder="请输入卡面卡号"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="芯片码" prop="physicalNum">
            <el-input
              v-model.trim="ruleForm.physicalNum"
              placeholder="请输入芯片码"
              maxlength="30"
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import Head from '@/components/head/index.vue';
import { updateChargeCard } from '@/service/apis/pile';

const router = useRouter();
const route = useRoute();
const {
  query: { id, cardNum, physicalNum },
} = route;
const ruleFormRef = ref<FormInstance>();

let ruleForm = reactive({
  id: id,
  cardNum: cardNum as any,
  physicalNum: physicalNum as any,
});
const rules = reactive<FormRules>({
  cardNum: [{ required: true, message: '请输入卡面卡号', trigger: 'blur' }],
  physicalNum: [{ required: true, message: '请输入芯片码', trigger: 'blur' }],
});

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid, fields: any) => {
    if (valid) {
      console.log('submit---', ruleForm);
      updateChargeCard(ruleForm).then((res) => {
        console.log('res===', res);
        emit('clear-cache');
        back();
      });
    } else {
      for (const key in ruleForm) {
        if (fields[key]) {
          ruleFormRef.value?.scrollToField(key);
          break;
        }
      }
    }
  });
};
</script>